package com.ogilvy.cms.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ogilvy.cms.bean.CmsLog;
import com.ogilvy.cms.bean.CmsTemplate;
import com.ogilvy.cms.bean.CmsUser;
import com.ogilvy.cms.util.ServiceDispatcher;
import com.ogilvy.common.JSONBean;
import com.ogilvy.common.MetaData;
import com.ogilvy.common.UtilTools;
import com.ogilvy.frame.action.BaseAction;
import com.ogilvy.frame.util.CmsConstants;

@SuppressWarnings("serial")
@Scope("prototype")
@Controller("cms.action.CmsTemplateAction")
public class CmsTemplateAction extends AdminAction{
	@Autowired
	protected ServiceDispatcher serviceDispatcher;
	private String rows;//前台以JSON的形式传递数据
	private int start;//分页开始
	private int limit;//每页显示量
	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}
	public String index(){
		return "index";
	}
	private CmsTemplate template=new CmsTemplate();
	List<CmsTemplate> datalist;
	/** 查询 */
	public void query(){
		
		if(rows==null){
			datalist=serviceDispatcher.getCmsTemplateService().query(template);
		}else{
			net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
			Map<String,String> screenMap=new HashMap<String, String>();
//			screenMap.put("cmtId", js.getString("cmtId"));
			screenMap.put("cmtName", js.getString("cmtName"));
			datalist=serviceDispatcher.getCmsTemplateService().queryByScreen(screenMap);
		}
		//采用集合分页
		List pageList = UtilTools.queryForPage(start, limit, datalist);
		JSONBean jbean = new JSONBean();
		MetaData md = new MetaData();
		
		md.setIdProperty("cmtId");//关联将要显示列表对应的bean实体的主键ID
		md.reflectFields("com.ogilvy.cms.bean.CmsTemplate");//关联将要显示列表对应的bean实体
		jbean.setMetaData(md);
		jbean.setRows(pageList);
		jbean.setSuccess(true);
		jbean.setTotal(datalist.size());

		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");

		//String jsonString = UtilTools.encodeObject2Json(jbean);
		String jsonString = UtilTools.encodeObject2Json(jbean,"MM/dd/yyyy HH:mm:ss");
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//return "true";
	}
	
	/** 修改 */
	public void modify(){
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		
		String tempid=js.getString("cmtId");
		int cmtId=Integer.parseInt(tempid);
		
		String cmtName=js.getString("cmtName");
		String copyName=js.getString("copyName");
		String cmtImg=js.getString("cmtImg");
		String cmtIcon=js.getString("cmtIcon");
		String cmtDesc=js.getString("cmtDesc");
		String cmtUrl=js.getString("cmtUrl");
		String cmtContent=js.getString("cmtContent");
		String pubsta=js.getString("cmtPubStatus");
		int cmtPubStatus=Integer.parseInt(pubsta);
		
		CmsUser cmsuser = getCmsUser();
		String cmtLastuser =cmsuser.getCmuName();//获取session中对象的姓名

		Date cmtLasttime=new Date();
		
		template.setCmtName(cmtName);
		template.setCmtImg(cmtImg);
		template.setCmtIcon(cmtIcon);
		template.setCmtDesc(cmtDesc);
		template.setCmtUrl(cmtUrl);
		template.setCmtContent(cmtContent);
		template.setCmtPubStatus(cmtPubStatus);
		template.setCmtLastuser(cmtLastuser);
		template.setCmtLasttime(cmtLasttime);
		
		template.setCmtId(cmtId);
		if(copyName.equals(cmtName)){
            serviceDispatcher.getCmsTemplateService().modify(template);
			
			JSONBean bean = new JSONBean();
			bean.setSuccess(true);
			//String jsonString = UtilTools.encodeObject2Json(bean);
			String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
			/**
			 * 系统日志
			 */
			CmsLog  log = UtilTools.buildLog("模板定义", CmsLog.MODIFY, "修改模板", cmtLastuser);
	        serviceDispatcher.getCmsLogService().add(log);
			PrintWriter out;
			try {
				out = ServletActionContext.getResponse().getWriter();
				out.print(jsonString);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			boolean isHave=serviceDispatcher.getCmsTemplateService().checkTemplateName(cmtName);
			if(isHave==false){
				serviceDispatcher.getCmsTemplateService().modify(template);
				
				JSONBean bean = new JSONBean();
				bean.setSuccess(true);
				//String jsonString = UtilTools.encodeObject2Json(bean);
				String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
				/**
				 * 系统日志
				 */
				CmsLog  log = UtilTools.buildLog("模板定义", CmsLog.MODIFY, "修改模板", cmtLastuser);
		        serviceDispatcher.getCmsLogService().add(log);
				PrintWriter out;
				try {
					out = ServletActionContext.getResponse().getWriter();
					out.print(jsonString);
					out.flush();
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				    StringBuffer jsonString =new StringBuffer();
		            jsonString.append("{");
		            jsonString.append("success:true,");
		            jsonString.append("isHave:true,");
		            jsonString.append("msg:'对不起,该模板已存在!'");
		            jsonString.append("}");
		        	 PrintWriter out;
		 	        try {
		 	            out = ServletActionContext.getResponse().getWriter();
		 	            out.print(jsonString);
		 	            out.flush();
		 	            out.close();
		 	        } catch (IOException e) {
		 	            e.printStackTrace();
		 	        }
		   }
		
		}
		
	}

	/** 删除 */
	public void del(){
		net.sf.json.JSONArray objArr = net.sf.json.JSONArray.fromObject(rows);
        for(int i=0;i<objArr.size();i++)
        {
        	net.sf.json.JSONObject js=objArr.getJSONObject(i);
        	serviceDispatcher.getCmsTemplateService().del(js.getInt("cmtId"));
        }
		
		JSONBean bean = new JSONBean();
		bean.setSuccess(true);
		String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
		
		CmsUser cmsuser = getCmsUser();
		String cmtLastuser =cmsuser.getCmuName();//获取session中对象的姓名
		/**
		 * 系统日志
		 */
		CmsLog  log = UtilTools.buildLog("模板定义", CmsLog.DELETE, "删除模板", cmtLastuser);
        serviceDispatcher.getCmsLogService().add(log);
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//return "delete";
	}
	
	/** 保存 */
	public void add(){
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		String cmtName=js.getString("cmtName");
		String cmtImg=js.getString("cmtImg");
		String cmtIcon=js.getString("cmtIcon");
		String cmtDesc=js.getString("cmtDesc");
		String cmtUrl=js.getString("cmtUrl");
		String cmtContent=js.getString("cmtContent");
		String pubsta=js.getString("cmtPubStatus");
		int cmtPubStatus=Integer.parseInt(pubsta);
		
		CmsUser cmsuser = getCmsUser();
		String cmtLastuser =cmsuser.getCmuName();//获取session中对象的姓名

		Date getDate=new Date();
		Date cmtLasttime=getDate;

		template.setCmtName(cmtName);
		template.setCmtImg(cmtImg);
		template.setCmtIcon(cmtIcon);
		template.setCmtDesc(cmtDesc);
		template.setCmtUrl(cmtUrl);
		template.setCmtContent(cmtContent);
		template.setCmtPubStatus(cmtPubStatus);
		template.setCmtLastuser(cmtLastuser);
		template.setCmtLasttime(cmtLasttime);
		
		boolean isHave=serviceDispatcher.getCmsTemplateService().checkTemplateName(cmtName);
		if(isHave==false){
			CmsTemplate templa=serviceDispatcher.getCmsTemplateService().add(template);
			JSONBean bean = new JSONBean();
			bean.setSuccess(true);
			// 需要新建一个具有id的vo返回给前台以便通知前台保存成功，不然前台一直处于编辑状态
			List rows = new ArrayList();
			rows.add(templa);
			bean.setRows(rows);
			//String jsonString = UtilTools.encodeObject2Json(bean);
			String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
			
			/**
			 * 系统日志
			 */
			CmsLog  log = UtilTools.buildLog("模板定义", CmsLog.Add, "添加模板", cmtLastuser);
	        serviceDispatcher.getCmsLogService().add(log);
			PrintWriter out;
			try {
				out = ServletActionContext.getResponse().getWriter();
				out.print(jsonString);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			 StringBuffer jsonString =new StringBuffer();
	            jsonString.append("{");
	            jsonString.append("success:true,");
	            jsonString.append("isHave:true,");
	            jsonString.append("msg:'对不起,该模板已存在!'");
	            jsonString.append("}");
	        	 PrintWriter out;
	 	        try {
	 	            out = ServletActionContext.getResponse().getWriter();
	 	            out.print(jsonString);
	 	            out.flush();
	 	            out.close();
	 	        } catch (IOException e) {
	 	            e.printStackTrace();
	 	        }
		}
		
	}
}
